package com.example.vue.sys.interceptor;

import com.auth0.jwt.JWT;
import com.example.vue.comm.util.IdUtil;
import com.example.vue.comm.util.WebUtil;
import com.example.vue.sys.domain.SysAccess;
import com.example.vue.sys.mapper.SysAccessMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author zhouxl
 * @DATE 2020/12/21
 * @descriptoin
 */
public class AccessInterceptor implements HandlerInterceptor {

    @Autowired
    private SysAccessMapper sysAccessMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("options".equals(request.getMethod().toLowerCase())) { // 预请求不做任何处理
            return true;
        }
        try {
            SysAccess sysAccess = createSysAccess(request);
            int row = sysAccessMapper.addSysAccess(sysAccess);
        } catch (Exception ex) {
            System.out.println(ex);
            return true;
        }
        return true;
    }

    /**
     * 构建访问的请求记录实体类信息
     *
     * @param request
     * @return
     */
    private SysAccess createSysAccess(HttpServletRequest request) {
        SysAccess sysAccess = new SysAccess();
        String token = request.getHeader("token");
        // token信息是否过期或者非法
        String accountNo = null;
        try {
            accountNo = JWT.decode(token).getClaim("accountNo").asString();
        } catch (Exception ex) {
            accountNo = null;
        }
        Map<String, Object> userAgentInfo = WebUtil.getUserAgentInfo(request);
        sysAccess.setAccessNo(IdUtil.uuid());
        sysAccess.setAccountNo(accountNo);
        sysAccess.setBroswer(userAgentInfo.get("browser").toString());
        sysAccess.setIp(request.getRemoteAddr());
        sysAccess.setIpAddress(request.getRemoteAddr());
        sysAccess.setCreateTime(new Date());
        sysAccess.setReqUrl(request.getRequestURI());
        sysAccess.setMethod(request.getMethod());
        return sysAccess;
    }
}
